using System.Configuration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace Nvigorate.Repository.Test
{
    public class TestSessionManager : ISessionManager
    {
        private ISessionFactory _sessionFactory;
        private ISession _session;

        public ISession GetCurrentSession()
        {
            if (_sessionFactory == null)
                InitSessionFactory();
            _session = _session ?? _sessionFactory.OpenSession();
            return _session;
        }

        protected void InitSessionFactory()
        {
            _sessionFactory = _sessionFactory ?? InitDatabase();
            HibernatingRhinos.NHibernate.Profiler.Appender.NHibernateProfiler.Initialize();
        }

        protected ISessionFactory InitDatabase()
        {
            return GetConfiguration().ExposeConfiguration(cfg =>
                                                              {
                                                                  new SchemaExport(cfg).Create(true, true);
                                                              }).BuildSessionFactory();
        }

        private FluentConfiguration GetConfiguration()
        {
            return Fluently.Configure()
                .Database(
                MsSqlConfiguration.MsSql2005.ConnectionString(
                    ConfigurationManager.ConnectionStrings["repository"].ConnectionString)
                    .AdoNetBatchSize(20)
                    .ShowSql)
                .Mappings(mapper => mapper.FluentMappings.AddFromAssemblyOf<Person>());
        }
    }
}